<?php

namespace Admin\Controller;

/**
 * 内容管理
 *
 * Class MemberController
 * @package Admin\Controller
 */
class MatchController extends AdminCommonController
{
    const MATCh_RANK = 9;
    const MOST_NOMINATION = 2;
    const MOST_VOTE = 20;

    /**
     * 比赛列表
     */
    public function index()
    {
        $model = M('match');
        $order = array(
            'matchtime' => 'desc'
        );
        $list = $model->where(array('del_flg' => 0))->order($order)->select();
        //$list['status'] = C('matchStatus')[$list['status']];
        $this->assign('match_info', $list);
        $this->display();
    }

    /**
     * 比赛发布
     */
    public function matchStatus()
    {
        $id = I('id');
        $status = I('status');

        $model = M('match');
        $res = $model->where(array('id' => $id))->save(array('status' => $status));
        //var_dump($res);exit;
        //echo $model->getLastSql();exit;
        if ($res !== false) {
            $status = 100;
            $message = '操作成功';
        } else {
            $status = 101;
            $message = '操作失败';
        }
        $this->showMessage(array(), $status, $message);
    }

    /**
     * 删除比赛
     *
     * @access public
     */
    public function delMatch()
    {
        $id = I('id');
        if (!$id) {
            $status = false;
            $message = '参数错误';
            $this->showMessage(array(), $status, $message);
        }
        $res = M('match')->where(array('id' => $id))->save(array('del_flg' => 1));
        //echo M('match')->getLastSql();exit;
        if ($res !== false) {
            $status = 100;
            $message = '操作成功';
        } else {
            $status = 101;
            $message = '操作失败';
        }
        $this->showMessage(array(), $status, $message);
    }

    /**
     * 比赛录入
     */
    public function matchInput()
    {
        $this->display();
    }

    /**
     * 比赛录入处理
     */
    public function doMatchInput()
    {
        //var_dump($_POST);exit;
        $name = I('name');
        $matchtime = I('matchtime');
        $matchplace = I('matchplace');

        if ($name && $matchtime && $matchplace) {
            $model = M('match');
            $data = array(
                'name'  => $name,
                'matchtime' =>strtotime( $matchtime),
                'matchplace'  => $matchplace,
                'status' => 0,
                'del_flg'  => 0
            );
            $res = $model->add($data);
            if ($res) {
                $status  = 100;
                $message = '录入成功';
                $this->showMessage(array(), $status, $message);
            } else {
                $status = 101;
                $message = '录入失败';
                $this->showMessage(array(), $status, $message);
            }
        } else {
            $status  = 101;
            $message = '参数错误';
            $this->showMessage(array(), $status, $message);
        }
    }

    /**
     * 种子选手设定
     *
     * http://127.0.0.1:8093/admin.php?s=/Match/seedList/match_id/1
     */
    public function seedList()
    {
        $match_id = I('match_id');
        if (!$this->checkMatchAvailable($match_id)) {
            $this->redirect('Public:error-500');
        }
        $list = $this->getSeedVote($match_id);
        $this->assign('list', $list);
        $this->assign('match_id', $match_id);
        $this->display();

    }

    /**
     * 种子选手详细
     */
    public function seedDetail()
    {
        $match_id = I('match_id');
        $seed_id  = I('seed_id');
        if (!$match_id || !$seed_id) {
            $this->redirect('Public:error-500');
        }
        $info = M('seed')->where(array('id' => $seed_id))->find();
        // 头像处理
        $info['photo_url'] = showImage($info['photo_url']);
        $this->assign('info', $info);

        $this->display();
    }

    /**
     * 种子选手初始化(录入30个)
     */
    public function seedAdd()
    {
        $match_id = I('match_id');
        $this->assign('match_id', $match_id);

        $this->display();
    }

    /**
     * 种子选手初始化处理
     */
    public function doSeedAdd()
    {
        $match_id  = I('match_id');
        $introduce = I('introduce');
        $phone     = I('phone');
        $name      = I('name');
        $fileData = $_FILES;

//        var_dump(key($fileData)); exit;
        // 最多添加30个
        $model = M('seed');
        $count = $model->where(array('match_id' => $match_id))->count();
        if (intval($count) >= 30) {
            $this->error('最多只能添加30个种子选手');
        }
        $data = array(
            'name'      => $name,
            'phone'     => $phone,
            'introduce' => $introduce,
            'match_id'  => $match_id,
            'create_time' => NOW_TIME
        );
        $seed_id = $model->add($data);

        $upload_path = $this->uploadImage($seed_id, key($fileData), $fileData, 'th_' ,null, false);
        $res = $model->where(array('id' => $seed_id))->save(array('photo_url' => $upload_path));
//        var_dump($upload_path); exit;
        if ($res) {
            $this->redirect('/Match/seedList', array('match_id' => $match_id));
        } else {
            $this->redirect('Public:error-500');
        }
    }

    public function delSeed()
    {
        $id =  I('id');
        if (!$id){
            $this->redirect('Public:error-500');
        }
        // 方法验证
        $where = array(
            'id' => $id
        );
        $model = M('seed');
        $data = $model->field('id')->where($where)->find();
        if(!$data) {
            $this->showMessage(array(), self::ERROR_CODE, '已删除，不能重复操作');
        }
        $res = $model->where($where)->delete();
        if ($res) {
            $this->showMessage();
        } else {
            $this->showMessage(array(), self::ERROR_CODE, self::ERROR_MSG);
        }
    }

    /**
     * 种子选手生成
     *
     * http://192.168.1.68:8093/admin.php?s=/Match/doGeneralSeed/match_id/2
     */
    public function doGeneralSeed()
    {
        // 获取上一次比赛的id
        $match_id = I('match_id');
        $prev_match_id = M('match')->where("id < $match_id")->order("id desc")->getField('id');
//        echo M('match')->getLastSql(); exit;
        // 比赛前九名(是否为种子选手)
        $where = array(
            'match_id' => $prev_match_id
        );
        $where['rank'] = array('elt', self::MATCh_RANK);
        $rank9 = M('match_result')->where($where)->select();
//        echo M('match_result')->getLastSql(); exit;
        // 判断9跟人是是否为种子选手
        $model = M('seed');
        if ($rank9) {
            foreach ($rank9 as $k1 => $v1) {
                if ($v1['type'] === '0') {
                    $data1[$k1]['name'] = M('member')->where(array('id' => $v1['member_id']))->getField('nickname');
                    $data1[$k1]['phone'] = '';  // 有问题
                    $data1[$k1]['introduce'] = '';
                } else if ($v1['type'] === '1') {
                    $seed_info = $model->where(array('id' => $v1['seed_id']))->find();
                    $data1[$k1]['name'] = $seed_info['name'];
                    $data1[$k1]['phone'] = $seed_info['phone'];
                    $data1[$k1]['introduce'] = $seed_info['phone'];
                }
                $data1[$k1]['match_id'] = $match_id;
            }
        }
        M()->startTrans();
//        var_dump($data1); exit;
        $res1 = $model->addAll($data1);
//        echo $model->getLastSql(); exit;
        // 上一轮比赛投票的前20人
        $most_vote_list = $this->getSeedVote($prev_match_id, self::MOST_VOTE);
//        var_dump($most_vote_list); exit;
        $data2 = array();
        foreach($most_vote_list as $k2 => $v2) {
            $data2[$k2]['name'] = $v2['name'];
            $data2[$k2]['phone'] = $v2['phone'];
            $data2[$k2]['introduce'] = $v2['introduce'];
            $data2[$k2]['match_id'] = $match_id;
        }
//        var_dump($data2); exit;
        $res2 = $model->addAll($data2);
//        echo $model->getLastSql();
//        exit;
        // 提名最多的2人
        $nomination = M('nomination')->field("id, name, count(name) as number, phone, introduce")
                                     ->where($where)
                                     ->limit(self::MOST_NOMINATION)
                                     ->group('name')
                                     ->order('count(name) desc')
                                     ->select();
//        echo M('nomination')->getLastSql(); exit;
//        var_dump($nomination); exit;
        $data3 = array();
        foreach ($nomination as $k3 => $v3) {
            $data3[$k3]['name'] = $v3['name'];
            $data3[$k3]['phone'] = $v3['phone'];
            $data3[$k3]['introduce'] = $v3['introduce'];
            $data3[$k3]['match_id'] = $match_id;
        }
//        var_dump($data3); exit;
        $res3 = $model->addAll($data3);
//        echo $model->getLastSql();
        if ($res1 && $res2 && $res3) {
            M()->commit();
            $this->showMessage();
        } else {
            M()->rollback();
            $this->showMessage(array(), self::ERROR_CODE, self::ERROR_MSG);
        }
    }

    /**
     * 比赛结果
     *
     * http://127.0.0.1:8093/admin.php?s=/match/result/match_id/1
     */
    public function result()
    {
        $match_id = I('match_id');
        if (!$match_id) {
            $this->redirect('Public:error-500');
        }
        $info = M('match')->where(array('match_id' => $match_id))->find();
        $list = M('match_result')->where(array('match_id' => $match_id))->order('rank asc')->select();
        if ($list) {
            foreach ($list as $key => $val) {
                if ($val['type'] == 1) { // 是种子选手
                    $list[$key]['name'] = M('seed')->where(array('id' => $val['seed_id']))->getField('name');
                } else {
                    $list[$key]['name'] = M('member')->where(array('id' => $val['member_id']))->getField('nickname');
                    $list[$key]['vs_seed_name'] = M('seed')->where(array('id' => $val['vs_seed_id']))->getField('name');
                }
            }
        }
//        var_dump($list); exit;
        $this->assign('info', $info);
        $this->assign('list', $list);
        $this->display();
    }

    /**
     * 添加结果页面
     */
    public function resultInput()
    {
        $match_id = I('match_id');
//        var_dump("dd"); exit;
        if (!$match_id) {
            $this->redirect('Public:error-500');
        }
        // 名称处理
        $rank = M('match_result')->where(array('match_id' => $match_id))->max('rank');
//        var_dump($rank); exit;
        $info = M('match')->where(array('match_id' => $match_id))->find();
        $this->assign('list1', $this->getMatchMemberList($match_id));
        $this->assign('list2', $this->getMatchSeedList($match_id));

        $this->assign('rank', intval($rank) + 1);
        $this->assign('info', $info);
        $this->display();
    }

    /**
     * 结果录入处理
     */
    public function doResultInput()
    {
//        var_dump($_POST); exit;

        $match_id = I('match_id');
        $result_id = I('result_id');
        $type = I('type' ,0 ,'int');
        $rank = I('rank');

        $vs_type = I('vs_type', 0, 'int');
        $vs_seed = I('vs_seed');

        if (!$match_id || !$result_id || !isset($type) || !$rank) {
            $this->redirect('Public:error-500');
        }

        // 同一名次不能录入两条数据
        $model = M('match_result');
        $where = array(
            'match_id' => $match_id,
            'rank' => $rank,
        );
        $has = $model->where($where)->find();
        if ($has) {
            $this->showMessage(array(), self::ERROR_CODE, '名次录入错误');
        }
        $data = array(
            'match_id' => $match_id,
            'type' => $type,
            'rank' => $rank,
            'create_time' => NOW_TIME,
        );
        if ($type === 1) {
            $data['seed_id'] = $result_id;
        } else {
            $data['member_id'] = $result_id;
        }
        if ($vs_type === 1) {
            $data['vs_type'] = $vs_type;
            $data['vs_seed_id'] = $vs_seed;
        }
//        var_dump($data); exit;
        $res = $model->add($data);
        if ($res) {
            $this->showMessage(array());
        } else {
            $this->showMessage(array(), self::ERROR_CODE, self::ERROR_MSG);
        }
    }

    /**
     * 报名信息一览
     *
     * @param $mid
     * @return mixed
     */
    protected function getMatchMemberList($mid)
    {
        $where = array(
            'n.match_id' => $mid,
            'n.type' => 2,
            'n.member_id' => array('NEQ', '')
        );
        $res = M('match_no n')->field('m.id, m.nickname AS name')
                              ->join("LEFT JOIN ddz_member m ON m.id = n.member_id")
                              ->where($where)
                              ->select();
        if (!$res) {
            return false;
        }
        return $res;
    }

    /**
     * 种子选手一览
     *
     * @param $mid
     * @return mixed
     */
    protected function getMatchSeedList($mid)
    {
        $where = array(
            'match_id' => $mid
        );
        $res = M('seed')->where($where)->select();
        if (!$res) {
            return false;
        }
        return $res;
    }
}